package com.github.defense.sync.data.http;

import com.github.defense.common.config.DefenseConfig;
import com.github.defense.common.utils.OkHttpTools;
import com.github.defense.sync.data.api.ClientRegisterDefenseRepository;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 通过此方式将当前应用的信息注册到defense-admin平台
 * @Author: lettger
 * @Date: 2021/12/2 下午2:28
 */
@Slf4j
public class HttpClientRegisterDefenseRepository implements ClientRegisterDefenseRepository {

    /**
     * 应用注册
     */
    public static final String URL_PATH = "/admin/application/register";

    private final List<String> serverList;

    private final Gson gson = new Gson();

    public HttpClientRegisterDefenseRepository(final DefenseConfig config) {
        this.serverList = Lists.newArrayList(Splitter.on(",").split(config.getAdminAddr()));
    }

    @Override
    public <T> void register(final T t) {
        this.execute(t,URL_PATH);
    }

    /**
     * 调用接口
     * @param t
     * @param path
     * @param <T>
     */
    private <T> void execute(final T t, final String path) {
        for (String server : serverList) {
            try {
                OkHttpTools.getInstance().post(server + path, gson.toJson(t));
                return;
            } catch (Exception e) {
                log.error("**** defense admin register data fail****", e);
            }
        }
    }
}
